package com.lujianfei.httprequest.okhttp;

import androidx.appcompat.app.AppCompatActivity;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import android.os.Bundle;
import android.util.Log;
import android.view.View;

import com.google.gson.Gson;
import com.lujianfei.httprequest.R;
import com.lujianfei.httprequest.intercepter.LogIntercepter;
import okhttp3.MediaType.Companion.toMediaTypeOrNull

import java.io.IOException;
import java.lang.StringBuilder
import java.util.HashMap;
import java.util.Map;
import kotlin.concurrent.thread

class OkhttpActivity : AppCompatActivity(), View.OnClickListener {

    val TAG = "OkhttpActivity==";

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_okhttp);
        findViewById<View>(R.id.btn_get_async).setOnClickListener(this)
        findViewById<View>(R.id.btn_get_sync).setOnClickListener(this)
        findViewById<View>(R.id.btn_post_async).setOnClickListener(this)
        findViewById<View>(R.id.btn_post_sync).setOnClickListener(this)
        findViewById<View>(R.id.btn_intercepter).setOnClickListener(this)
    }

    override fun onClick(view: View) {
        when (view.id) {
            R.id.btn_get_async -> {
                getAsync()
            }
            R.id.btn_get_sync -> {
                thread {
                    getSync()
                }
            }
            R.id.btn_post_async -> {
                postAsync()
            }
            R.id.btn_post_sync -> {
                thread {
                    postSync()
                }
            }
            R.id.btn_intercepter -> {
                thread {
                    postSyncWithIntercepter()
                }
            }
        }
    }

    fun getAsync() {
        // 异步 Get 请求
        val url = "http://www.baidu.com";
        val okHttpClient = OkHttpClient()
        val request = Request.Builder()
                .url(url)
                .get()//默认就是GET请求，可以不写
                .build();
        val call = okHttpClient.newCall(request);
        call.enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
            }

            override fun onResponse(call: Call, response: Response) {
                Log.d(TAG, "onResponse: " + response.body?.string())
            }
        })
    }

    private fun getSync() {
        // 同步 Get 请求
        val url = "http://www.baidu.com"
        val okHttpClient = OkHttpClient();
        val request = Request.Builder()
                .url(url)
                .get()//默认就是GET请求，可以不写
                .build()
        val call = okHttpClient.newCall(request);
        try {
            val response = call.execute();
            Log.d(TAG, "onResponse: " + response.body?.string());
        } catch (e:Exception) {
            e.printStackTrace();
        }
    }

    private fun postAsync() {
        val map = HashMap<String,String>()
        map["wd"] = "大神"
        val gson = Gson()
        val url = "http://www.baidu.com/s"
        val request = Request.Builder()
                .post(RequestBody.create("application/json;charset=utf-8".toMediaTypeOrNull(),gson.toJson(map)))
                .url(url)
                .build();
        val okHttpClient = OkHttpClient()
        val call = okHttpClient.newCall(request);
        call.enqueue(object : Callback{
            override fun onFailure(call: Call, e: IOException) {
            }

            override fun onResponse(call: Call, response: Response) {
                Log.d(TAG, "onResponse: " + response.body?.string())
            }
        })
    }

    private fun postSync() {
        val map = HashMap<String,String>()
        map["wd"] = "大神";
        val gson = Gson()
        val url = "http://www.baidu.com/s"
        val request = Request.Builder()
                .post(RequestBody.create("application/json;charset=utf-8".toMediaTypeOrNull(),gson.toJson(map)))
                .url(url)
                .build();
        val okHttpClient = OkHttpClient()
        val call = okHttpClient.newCall(request);
        try {
            val response = call.execute();
            Log.d(TAG, "onResponse: " + response.body?.string());
        } catch (e:Exception) {
            e.printStackTrace();
        }
    }

    private fun postSyncWithIntercepter() {
        val map = HashMap<String,String>()
        map["wd"] = "大神";
        val gson = Gson()
        val url = "http://www.baidu.com/s"
        val request = Request.Builder()
                .post(RequestBody.create("application/json;charset=utf-8".toMediaTypeOrNull(),gson.toJson(map)))
                .url(url)
                .build();
        val okHttpClient = OkHttpClient.Builder()
                .addNetworkInterceptor(LogIntercepter())
                .build();
        val call = okHttpClient.newCall(request);
        try {
            val response = call.execute()
            Log.d(TAG, "onResponse: " + response.body?.string());
        } catch (e:Exception) {
            e.printStackTrace();
        }
    }

}
